<template>
  <!-- 检出流程判断 检出零件时，是否创建新版本？零件检出时，是否给所有借用者发送消息 -->
  <BasicModal
    v-bind="$attrs"
    title="检出流程"
    @register="registerCheckOutModal"
    @ok="handleCheckOut"
    @cancel="cancelCheckOut"
    :destroyOnClose="true"
    :minHeight="100"
    :width="400"
  >
    <BasicForm @register="registerCheckoutForm" />
  </BasicModal>
  <initiateFlowCopy @register="registerModalCopy" />
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import initiateFlowCopy from '/@/views/demo/workFlow/initiateFlowCopy.vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { checkoutSchemas } from './tableData';
  import { PartJustCheckOut } from '/@/api/demo/partManager';

  const emit = defineEmits(['register', 'success']);
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const currentRecord = ref<any>(null);
  const isFrom = ref<string>('');

  const [registerModalCopy, { openModal: openModalCopy }] = useModal();
  // 检出流程
  const [registerCheckoutForm, { resetFields, getFieldsValue }] = useForm({
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
    schemas: checkoutSchemas(),
    showActionButtonGroup: false,
  });
  const [registerCheckOutModal, { closeModal: closeCheckOutModal }] = useModalInner((data) => {
    resetFields();
    currentRecord.value = data.record;
    isFrom.value = data.type;
  });

  const handleCheckOut = () => {
    if (isFrom.value === '检出零件') {
      openModalCopy(true, {
        record: currentRecord.value,
        type: '检出流程',
        selectedFiles: '',
        projectid: '',
        projectName: '',
        taskName: '',
        formId: '',
        state: '零件',
        isUpdate: false,
        createNewVersion: getFieldsValue().createNewVersion,
        sendMessage: getFieldsValue().sendMessage,
      });
      cancelCheckOut();
    } else if (isFrom.value === '直接检出') {
      PartJustCheckOut(
        currentRecord.value.id,
        getFieldsValue().createNewVersion,
        getFieldsValue().sendMessage,
      ).then(() => {
        emit('success');
        cancelCheckOut();
        createMessage.success(t('routes.demo.partManager.checkOutPartSuccess'));
      });
    }
  };
  const cancelCheckOut = () => {
    currentRecord.value = null;
    isFrom.value = '';
    closeCheckOutModal();
  };
</script>
